<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联单据" prop="baoName">
        <el-input v-model="queryParams.baoName" placeholder="请输入关联单据" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库" prop="kuId">
        <el-input v-model="queryParams.kuId" placeholder="请输入仓库" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['jiuzai:wuzibaofei:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="View" @click="handleBatchView"
          v-hasPermi="['jiuzai:wuziruku:query']">查看</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['jiuzai:wuzibaofei:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['jiuzai:wuzibaofei:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['jiuzai:wuzibaofei:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wuzibaofeiList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="baoId" />
<el-table-column label="用户" align="center" prop="yId">
  <template #default="scope">
    <span>{{ scope.row.yId }}</span> 
  </template>
</el-table-column>
      <el-table-column label="关联单据" align="center" prop="baoName" />
      <el-table-column label="备注" align="center" prop="baoBeizhu" />
      <el-table-column label="仓库" align="center" prop="kuId">
        <template #default="scope">
          <span v-if="scope.row.kuId">{{ scope.row.ku.kuName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['jiuzai:wuzibaofei:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['jiuzai:wuzibaofei:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改物资报废对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="wuzibaofeiRef" :model="form" :rules="rules" label-width="80px">
<el-form-item label="操作人" prop="yId">
  <el-input 
    v-model="currentUserName" 
    placeholder="当前用户" 
    :disabled="true" 
  />
  <!-- 隐藏字段确保表单提交时包含yId -->
  <input type="hidden" v-model="form.yId" />
</el-form-item>
        <el-form-item label="关联单据" prop="baoName">
          <el-select v-model="form.baoName" placeholder="请选择关联单据">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="baoBeizhu">
          <el-input v-model="form.baoBeizhu" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="仓库" prop=kuId>
          <el-select v-model="form.kuId" placeholder="请选择仓库">
            <el-option v-for="item in cangkuList" :key="item.kuId" :label="item.kuName" :value="item.kuId" />
          </el-select>
        </el-form-item>

        <div style="margin: 20px 0;">
          <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
            <span style="font-weight: bold;">报废物资明细</span>
            <el-button type="primary" size="small" v-if="TIANJIA" @click="openSecondDialog">添加物资</el-button>
          </div>

          <el-table :data="form.detailList" border style="width: 100%" size="small">
            <el-table-column label="物资品名" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.wuziName" placeholder="请输入物资品名" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="计量单位" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.wuziDanwei" placeholder="请输入单位" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="报废数量" width="120">
              <template #default="scope">
                <el-input-number v-model="scope.row.baofeiShuliang" :min="1" :max="scope.row.originalQuantity"
                  size="small" style="width: 100%" :disabled="!TIANJIA" @change="validateQuantity(scope.row)" />
                <div v-if="scope.row.baofeiShuliang > scope.row.originalQuantity" style="color: red; font-size: 12px;">
                  报废数量不能超过库存数量({{ scope.row.originalQuantity }})
                </div>
              </template>
            </el-table-column>
            <el-table-column label="报废原因">
              <template #default="scope">
                <el-input v-model="scope.row.baofeiYuanyin" placeholder="请输入报废原因" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60" align="center">
              <template #default="scope">
                <el-button link type="danger" size="small" @click="removeMaterialRow(scope.$index)" v-if="TIANJIA">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <el-dialog title="物资明细" v-model="secondDialogVisible" width="700px" append-to-body>
        <div>物资明细</div>
        <el-table :data="detailData" border style="width: 100%">
          <el-table-column prop="wuziName" label="物资名称" width="180" />
          <el-table-column prop="wuziDanwei" label="规格" width="180" />
          <el-table-column prop="wuziShu" label="库存数量" width="120" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="addSelectedMaterial(scope.row)">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="基本信息" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="编号">{{ viewForm.baoId }}</el-descriptions-item>
        <el-descriptions-item label="出库仓库">
          <span v-if="viewForm.kuId === viewForm.kuId">
            {{ viewForm.ku?.kuName }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <div style="flex-grow: 1; overflow: hidden; display: flex; flex-direction: column; padding: 0 20px 20px;">
        <div style="font-weight: bold; margin: 10px 0 5px 0;">物资明细</div>
        <div style="flex-grow: 1; overflow: auto;">
          <el-table :data="detailData1 ? [detailData1] : []" border size="small" style="width: 100%;">
            <el-table-column prop="wuziMing" label="物资名称" fixed />
            <el-table-column prop="wuziGuige" label="规格" />
            <el-table-column prop="wuziShu" label="数量" align="center" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Wuzibaofei">
import { listWuzibaofei, getWuzibaofei, delWuzibaofei, addWuzibaofei, updateWuzibaofei } from "@/api/jiuzai/wuzibaofei"
import { listCangku } from "@/api/cangku/cangku"
import { listWuzixinxi } from "@/api/jiuzai/wuzixinxi"
import { addBaofeimingxi, getBaofeimingxi, updateBaofeimingxi } from "@/api/jiuzai/baofeimingxi"
import { updateWuzixinxi } from "@/api/jiuzai/wuzixinxi"
import { ref } from "vue"
import { listWuzi } from "@/api/jiuzai/wuzi"
import { getInfo } from '@/api/login'

const { proxy } = getCurrentInstance()

const wuzibaofeiList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
let TIANJIA = ref(true)
const ids = ref([])
const single = ref(true)
const viewForm = ref({})
const viewOpen = ref(false)
const multiple = ref(true)
const total = ref(0)
const cangkuList = ref([])
const title = ref("")
const options = ref([
  { label: '盘点单', value: '盘点单' },
  { label: '物资回收', value: '物资回收' },
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    baoName: null,
    kuId: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询物资报废列表 */
function getList() {
  loading.value = true
  listWuzibaofei(queryParams.value).then(response => {
    wuzibaofeiList.value = response.rows
    console.log(wuzibaofeiList)
    total.value = response.total
    loading.value = false
  })
}

const currentUserName = ref('')
// 获取用户信息
const fetchCurrentUser = async () => {
  try {
    const response = await getInfo()
    currentUserName.value = response.user.nickName || response.user.userName
    form.value.yId = currentUserName.value // 直接使用用户名作为yId
  } catch (error) {
    console.error('获取用户信息失败:', error)
    currentUserName.value = '系统用户'
  }
}


const secondDialogVisible = ref(false)
const detailData = ref([])
const detailData1 = ref({})
const wuziList = ref({})

const openSecondDialog = () => {
  secondDialogVisible.value = true
  listWuzixinxi().then(response => {
    detailData.value = response.rows
  })
}

const reset = () => {
  form.value = {
    baoId: null,
    yId: null,
    baoName: null,
    baoBeizhu: null,
    kuId: null,
    shenheDate: null,
    shenheUser: null,
    shenheBeizhu: null,
    shenheZhuangtai: null,
    detailList: []
  }
  proxy.resetForm("wuzibaofeiRef")
}

const addSelectedMaterial = (material) => {
  form.value.detailList.push({
    wuziId: material.wuziId,
    wuziName: material.wuziName,
    wuziGuige: material.wuziGuige,
    wuziShu: material.wuziShu,
    wuziDanwei: material.wuziDanwei,
    baofeiShuliang: 1,
    baofeiYuanyin: '',
    originalQuantity: material.wuziShu
  })
  secondDialogVisible.value = false
}

const removeMaterialRow = (index) => {
  form.value.detailList.splice(index, 1)
}

function cancel() {
  open.value = false
  reset()
}

function getCangkuList() {
  loading.value = true
  listCangku(queryParams.value).then(response => {
    cangkuList.value = response.rows
    loading.value = false
  })
}

const validateQuantity = (row) => {
  if (row.baofeiShuliang > row.originalQuantity) {
    proxy.$message.warning(`报废数量不能超过库存数量(${row.originalQuantity})`)
    row.baofeiShuliang = row.originalQuantity
  }
}
function getjueseList() {
  loading.value = true
  listWuzi(queryParams.value).then(response => {
    wuziList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
onMounted(() => {
  getjueseList()
  getCangkuList()
  fetchCurrentUser()
})





function handleBatchView() {
  if (ids.value.length === 0) {
    proxy.$message.warning("请先选择要查看的记录");
    return;
  }
  if (ids.value.length > 1) {
    proxy.$message.warning("只能选择一条记录查看");
    return;
  }

  const bao_id = ids.value[0];
  getWuzibaofei(bao_id).then(response => {
    viewForm.value = response.data;
    console.log(viewForm.value);
    viewOpen.value = true;
  });
  getBaofeimingxi(bao_id).then(response => {
    detailData1.value = response.data;
    console.log(detailData1.value);
  });
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.baoId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  TIANJIA.value = true
  reset()
  open.value = true
  title.value = "添加物资报废"
  // 自动设置当前用户
  form.value.yId = currentUserName.value
}

function handleUpdate(row) {
  TIANJIA.value = false
  reset()
  const _baoId = row.baoId || ids.value

  getWuzibaofei(_baoId).then(mainRes => {
    form.value = {
      ...mainRes.data,
      detailList: []
    }
    // 保持原有的yId不覆盖
    open.value = true
    title.value = "修改物资报废"

    return getBaofeimingxi(_baoId)
  }).then(detailRes => {
    if (detailRes.data) {
      form.value.detailList = [{
        wuziId: detailRes.data.wuziId,
        baomingId: detailRes.data.baomingId,
        wuziName: detailRes.data.wuziMing || '无名称',
        wuziDanwei: detailRes.data.wuziGuige || '无单位',
        baofeiShuliang: Number(detailRes.data.wuziShu) || 1,
        baofeiYuanyin: detailRes.data.wuziBaofei || '无原因',
        originalQuantity: Number(detailRes.data.wuziShu) || 1
      }]
    }
  }).catch(error => {
    console.error("数据加载失败:", error)
    proxy.$modal.msgError("数据加载失败")
  })
}

const submitForm = () => {
  proxy.$refs["wuzibaofeiRef"].validate(valid => {
    if (valid) {
      if (!form.value.detailList || form.value.detailList.length === 0) {
        proxy.$modal.msgWarning("请至少添加一条报废物资明细")
        return
      }

      const hasExceeded = form.value.detailList.some(item =>
        item.baofeiShuliang > item.originalQuantity
      )
      if (hasExceeded) {
        proxy.$modal.msgWarning("有物资的报废数量超过了库存数量，请修改")
        return
      }

      if (form.value.baoId != null) {
        updateWuzibaofei(form.value).then(mainRes => {
          if (mainRes.code !== 200) {
            proxy.$modal.msgError("主表更新失败：" + mainRes.msg)
            return Promise.reject(mainRes.msg)
          }

          const detailList = form.value.detailList
          const updateDetailPromises = detailList.map(item => {
            return updateBaofeimingxi({
              baomingId: item.baomingId,
              wuziId: item.wuziId,
              wuziShu: item.baofeiShuliang,
              baoId: form.value.baoId,
              kuId: form.value.kuId,
              baomingZt: 1,
              wuziGuige: item.wuziDanwei,
              wuziMing: item.wuziName,
              wuziBaofei: item.baofeiYuanyin
            })
          })

          return Promise.all(updateDetailPromises)
        }).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error("修改失败：", error)
          proxy.$modal.msgError("修改失败：" + (error || "未知错误"))
        })
            } else {
        loading.value = true // 显示加载状态
        addWuzibaofei(form.value)
          .then(response => {
            if (response.code !== 200) {
              throw new Error(response.msg || "新增失败")
            }
            return Promise.all([
              addBaofeimingxi1(response.data, form.value.kuId),
              ...form.value.detailList.map(item => 
                updateWuzixinxi({
                  wuziId: item.wuziId,
                  wuziShu: item.originalQuantity - item.baofeiShuliang
                })
              )
            ])
          })
          .then(() => {
            proxy.$modal.msgSuccess("新增成功，库存已更新")
            open.value = false
            getList() // 确保刷新列表
          })
          .catch(error => {
            console.error("操作失败:", error)
            proxy.$modal.msgError(error.message || "操作失败")
          })
          .finally(() => {
            loading.value = false
          })
      }
    }
  })
}

function addBaofeimingxi1(baoid, kuid) {
  return new Promise((resolve, reject) => {
    const detailList = form.value.detailList;
    if (!detailList || detailList.length === 0) return resolve();
    
    const promises = detailList.map(item => {
      return addBaofeimingxi({
        wuziId: item.wuziId,
        wuziShu: item.baofeiShuliang,
        baoId: baoid,
        kuId: kuid,
        baomingZt: 1,
        wuziGuige: item.wuziDanwei,
        wuziMing: item.wuziName,
        wuziBaofei: item.baofeiYuanyin
      });
    });
    
    Promise.all(promises)
      .then(() => resolve())
      .catch(error => reject(error))
  })
}

function handleDelete(row) {
  const _baoIds = row.baoId || ids.value
  proxy.$modal.confirm('是否确认删除物资报废编号为"' + _baoIds + '"的数据项？').then(function () {
    return delWuzibaofei(_baoIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

function handleExport() {
  proxy.download('jiuzai/wuzibaofei/export', {
    ...queryParams.value
  }, `wuzibaofei_${new Date().getTime()}.xlsx`)
}

getList()
</script>